package com.wangzz.mallchat.common.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;

import java.util.Optional;

public class MyHeaderCollectHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 解析消息头
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(req.getUri());
            Optional<String> tokenOptional = Optional.of(urlBuilder)
                    .map(builder -> builder.getQuery())
                    .map(query -> query.get("token"))
                    .map(CharSequence::toString);
            // 不为空
            // 将token绑定到channel
            tokenOptional.ifPresent(s -> NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, s));
            // 重新将url设置成websocket路径不带token，否则后面的握手，会对配置的"/"，和自己的路径进行比较相同才会进行握手
            // 只获取路径，不拿参数
            // 之前路径
            // /?token=xxx 修改后为 /
            req.setUri(urlBuilder.getPath().toString());
        }
        // 后续处理器继续处理
        ctx.fireChannelRead(msg);
    }
}
